<?php

declare(strict_types=1);

namespace app\api\service;

use app\common\ApiClient;
use think\facade\Log;
use think\facade\Db;

class GoAffPro
{

    protected $apiClient;
    protected $env;
    protected $baseUrl;
    // protected $logFullResponse;
    protected $headers;



    public function __construct()
    {


        $this->env = env('APP_ENV', 'dev');

        $this->baseUrl = config('domain.' . $this->env . '.goaffpro');
        $this->apiClient = new ApiClient($this->baseUrl);
        $this->headers = [
            'Accept' => 'application/json',
            'x-goaffpro-access-token' => env('GOAFFPRO_X-GOAFFPRO-ACCESS-TOKEN')
        ];
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-05-13 19:32:51 
     * @param [type] @required
     * @return Renderable
     */
    public function updateAffiliateOrder(bool $status, int $orderId)
    {

        if ($orderId && $orderId > 0) {
            $orderInfo = Db::name('order_relation')->where('order_id', $orderId)->find();
            if (!$orderInfo) {
                // 如果订单关联信息不存在，返回错误
                return [
                    'code' => 1,
                    'message' => '订单关联信息错误',
                    'data' => null
                ];
            }
            if ($orderInfo['affiliate_id']) {
                $orderStatus = $status ? 'approved' : 'rejected';
                $path = '/v1/admin/orders/' . $orderInfo['affiliate_id'];
                $data = [
                    'status' => $orderStatus,
                ];
                $options = [
                    'headers' => $this->headers,
                    'form_params' => $data
                ];

                $this->apiClient->setLogFullResponse(true);
                $response = $this->apiClient->overallPatch($path, $options);

                if (!isset($response['status']) || $response['status'] !== 200) {
                    throw new \Exception('修改GoAffPro订单API请求失败: ' . ($response['message'] ?? '未知错误') . 'httpstatus:' . $response['status'] ?? "");
                }

                if (!isset($response['body']['status'])) {
                    throw new \Exception('修改GoAffPro订单响应数据格式错误:' . json_encode($response['body'], JSON_UNESCAPED_UNICODE));
                }
            }
            // 如果订单状态为 false (取消订单)，则清空 discount_id 和 discount_code
            if (!$status) {
                Db::name('order_relation')->where('order_id', $orderId)->update([
                    'discount_id' => null,
                    'discount_code' => null
                ]);
                return ['code' => 0, 'message' => '折扣信息已清除', 'data' => null];
            }
        } else {
            return [
                'code' => 1,
                'message' => '订单ID错误',
                'data' => null
            ];
        }
    }

    /**
     * @describe 创建推广员订单
     * @author: Bobo
     * @date: 2025-05-13 11:39:04 
     * @param [type] @required
     * @return Renderable
     */

    public function createAffiliateOrder(string $AffiliateInfo, array $orderInfo)
    {
        try {
            // 1. 验证数据并获取解析后的推广员信息
            $parsedAffiliateInfo = $this->validateAffiliateData($AffiliateInfo, $orderInfo);

            // 2. 创建订单
            $this->createGoAffProOrder($parsedAffiliateInfo, $orderInfo);

            // 3. 查询订单
            $result = $this->searchGoAffProOrderAndHandle($orderInfo['number'], $orderInfo['id']);
            return [
                'code' => 0,
                'message' => 'success',
                'data' => $result
            ];
        } catch (\Exception $e) {
            Log::error(
                '创建推广员订单失败：' . $e->getMessage() .
                    ' | 文件：' . $e->getFile() .
                    ' | 行号：' . $e->getLine() .
                    ' | 数据：' . json_encode([
                        'affiliate_info' => $AffiliateInfo ?? [],
                        'order_info' => $orderInfo ?? []
                    ], JSON_UNESCAPED_UNICODE)
            );

            return [
                'code' => 1,
                'message' => '创建推广员订单失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }

    /**
     * 创建GoAffPro订单
     */
    private function createGoAffProOrder(array $affiliateInfo, array $orderInfo)
    {
        $path = '/v1/admin/orders';
        $data = [
            'affiliate_id' => $affiliateInfo['id'],
            'ref_code' => $affiliateInfo['ref_code'],
            'order' => $orderInfo
        ];

        $options = [
            'headers' => $this->headers,
            'form_params' => $data
        ];

        $this->apiClient->setLogFullResponse(true);
        $response = $this->apiClient->overallPost($path, $options);

        if (!isset($response['status']) || $response['status'] !== 200) {
            throw new \Exception('创建GoAffPro订单API请求失败: ' . ($response['message'] ?? '未知错误'));
        }

        if (!isset($response['body']['result'])) {
            throw new \Exception('创建GoAffPro订单响应数据格式错误:' . json_encode($response['body'], JSON_UNESCAPED_UNICODE));
        }

        if (isset($response['body']['result']['site_id'])) {
            throw new \Exception('创建GoAffPro订单错误:' . $response['body']['result']['error']);
        }

        return $response['body']['result'];
    }

    /**
     * 查询GoAffPro订单
     */
    private function searchGoAffProOrderAndHandle(string $orderNumber, int $orderId)
    {
        $path = '/v1/admin/orders';
        $data = [
            'number' => $orderNumber,
            'fields' => 'id,affiliate_id,number,total,subtotal,commission,status,sub_id,coupons,mlm_amount,created,type,customer_email,is_new_customer,line_items,shipping_address,customer,is_paid'
        ];

        $options = [
            'headers' => $this->headers,
            'query' => $data
        ];

        $response = $this->apiClient->overallGet($path, $options);

        if (!isset($response['status']) || $response['status'] !== 200) {
            throw new \Exception('查询GoAffProAPI请求订单失败: ' . ($response['message'] ?? '未知错误'));
        }

        if (!isset($response['body']['orders'])) {
            throw new \Exception('查询GoAffPro订单响应数据格式错误:' . json_encode($response['body'], JSON_UNESCAPED_UNICODE));
        }

        if (count($response['body']['orders']) < 1) {
            throw new \Exception('查询GoAffPro订单错误: 不存在GoAffPro订单');
        }
        $orders = $response['body']['orders'][0];
        return $orders;
        // // 先查询是否存在
        // $exists = Db::name('order_relation')
        //     ->where([
        //         'order_id' => $orderId,
        //         'aff_order_id' => $orders['id'],
        //         'affiliate_id' => $orders['affiliate_id']
        //     ])
        //     ->find();

        // // 不存在才插入
        // if (!$exists) {
        //     $res = Db::name('order_relation')->insert([
        //         'order_id' => $orderId,
        //         'aff_order_id' => $orders['id'],
        //         'affiliate_id' => $orders['affiliate_id'],
        //         'create_time' => date('Y-m-d H:i:s')
        //     ]);
        // }

        // if (!$exists && !$res) {
        //     throw new \Exception('查询GoAffPro订单保存关联订单失败');
        // }
    }

    /**
     * 验证数据
     */
    private function validateAffiliateData($affiliateInfo, $orderInfo)
    {
        $affiliateInfo = json_decode($affiliateInfo, true);

        if (empty($affiliateInfo)) {
            throw new \Exception('推广员信息错误');
        }
        if (!isset($affiliateInfo['id']) || !isset($affiliateInfo['ref_code'])) {
            throw new \Exception('推广员信息错误');
        }
        if (empty($affiliateInfo['id']) || empty($affiliateInfo['ref_code'])) {
            throw new \Exception('推广员信息错误');
        }
        if (empty($orderInfo)) {
            throw new \Exception('订单信息错误');
        }
        if (!isset($orderInfo['id']) || !isset($orderInfo['number']) || !isset($orderInfo['total']) || !isset($orderInfo['subtotal'])) {
            throw new \Exception('订单信息错误');
        }
        if (empty($orderInfo['id']) || empty($orderInfo['number'])) {
            throw new \Exception('订单信息错误');
        }
        if (!isset($orderInfo['line_items']) || !is_array($orderInfo['line_items'])) {
            throw new \Exception('订单信息错误');
        }

        return $affiliateInfo;
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-05-12 17:31:56 
     * @param [type] @required
     * @return Renderable
     */
    public function searchAffiliate($res_code)
    {
        try {
            // 1. 先进行 API 请求
            $path = '/v1/admin/affiliates/search';
            $data = [
                'in' => 'ref_code',
                'keyword' => $res_code,
                'fields' => 'id,name,first_name,last_name,email,ref_code,ref_codes,coupon,coupons,phone,facebook,twitter,instagram,address_1,address_2,city,state,zip,country,phone,extra_1,extra_2,extra_3,group_id,registration_ip,personal_message,admin_note,payment_method,payment_details,commission,status,last_login,total_referral_earnings,total_network_earnings,total_amount_paid,total_amount_pending,total_other_earnings,number_of_orders'
            ];

            $options = [
                'headers' => $this->headers,
                'query' => $data
            ];

            $this->apiClient->setLogFullResponse(true);
            $response = $this->apiClient->overallGet($path, $options);

            // 2. 验证响应数据
            if (!isset($response['status']) || $response['status'] !== 200) {
                throw new \Exception('API 请求失败: ' . ($response['message'] ?? '未知错误'));
            }

            if (!isset($response['body']['result']['affiliates'])) {
                throw new \Exception('响应数据格式错误');
            }

            $affiliates = $response['body']['result']['affiliates'];
            if (empty($affiliates)) {
                return [
                    'code' => 0,
                    'message' => '未找到推广员',
                    'data' => null
                ];
            }

            // 3. 处理推广员数据
            $affiliate = $affiliates[0];
            if (!isset($affiliate['id']) || !isset($affiliate['ref_code'])) {
                throw new \Exception('推广员数据不完整');
            }

            // 4. 开启事务 - 只包含数据库操作
            Db::startTrans();
            try {
                // 处理折扣数据
                $discount_res = Db::name('discount')->where([
                    'is_del' => 0,
                    'source' => 2
                ])->find();

                if (!$discount_res) {
                    Db::name('discount')->save([
                        'discount_category' => 2,
                        'discount_parent_category' => 2,
                        'method' => 2,
                        'code_title' => 'GoAffPro',
                        'discount_type' => 1,
                        'discount_value' => 1,
                        'activedate_start' => date('Y-m-d H:i:s'),
                        'creator' => 1,
                        'create_time' => date('Y-m-d H:i:s'),
                        'source' => 2
                    ]);
                }

                // 处理优惠券数据
                if (!isset($affiliate['coupons']) || !is_array($affiliate['coupons'])) {
                    throw new \Exception('优惠券数据格式错误');
                }

                $insert_data = array_map(function ($coupon) use ($affiliate) {
                    return [
                        'affiliate_id' => $affiliate['id'],
                        'coupon_code' => $coupon['code'],
                        'discount_value' => $coupon['discount_value'],
                        'discount_type' => $coupon['discount_type'],
                        'create_time' => date('Y-m-d H:i:s'),
                    ];
                }, $affiliate['coupons']);

                // 更新数据库
                Db::name('aff_coupons')->where('affiliate_id', $affiliate['id'])->delete();
                Db::name('aff_coupons')->insertAll($insert_data);

                // 提交事务
                Db::commit();

                return [
                    'code' => 0,
                    'message' => 'success',
                    'data' => [
                        'id' => $affiliate['id'],
                        'ref_code' => $affiliate['ref_code']
                    ]
                ];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            Log::error(
                '搜索推广员失败：' . $e->getMessage() .
                    ' | 文件：' . $e->getFile() .
                    ' | 行号：' . $e->getLine() .
                    ' | 路径：' . ($path ?? 'null') .
                    ' | 数据：' . json_encode($data ?? [], JSON_UNESCAPED_UNICODE)
            );

            return [
                'code' => 1,
                'message' => '搜索推广员失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
}
